import React from "react";
import { Button, Form, Select, Spin, message } from "antd";
import { messages } from "share/common";
import GrantRangeSelector from "containers/data-center/report-distribution/grant-range-selector";
import contractService from "containers/contract/contract.service";
import errorMessage from "share/errorMessage";
import { connect } from "react-redux";

const FormItem = Form.Item;
const Option = Select.Option;

@connect(mapStateToProps)
class ContractAuthorize extends React.Component {
  state = {
    loading: false,
    selectedGrantArray: [],
    grantType: "user",
  };

  componentDidMount() {
    this.getGrantDetail();
  }

  getGrantDetail = (grantType) => {
    const { contractHeaderId } = this.props;
    this.setState({ loading: true });
    contractService
      .getGrantDetail({ contractHeaderId, grantType })
      .then((res) => {
        this.setState({
          selectedGrantArray: (res.data.grant || [])
            .map((i) => (res.data.grantType === "userGroup" ? i.userGroup : i.user))
            .filter((i) => !!i),
          grantType: res.data.grantType,
          loading: false,
        });
      })
      .catch((e) => {
        errorMessage(e.response);
        this.setState({ loading: false });
      });
  };

  onChangeSelectedGrantArray = ({ result }) => {
    this.setState({
      selectedGrantArray: result,
    });
  };

  saveGrantDetail = () => {
    const { contractHeaderId, tenant } = this.props;
    const { selectedGrantArray } = this.state;
    const currentGrant = this.props.form.getFieldValue("grant");
    this.setState({ loading: true });
    let params = {
      enable: true,
      contractHeaderId,
      grantType: currentGrant,
      grant: selectedGrantArray.map((i) => {
        let v = {};
        v.grantProp = currentGrant;
        v.grantDesc = currentGrant === "user" ? "指定人员" : "指定人员组";
        v.grantValue = currentGrant === "user" ? i.userOID : i.userGroupOID;
        return v;
      }),
      tenantId: tenant.id,
    };
    contractService
      .saveGrantDetail(params)
      .then((res) => {
        message.success(messages("finance-6.key146") /*保存成功*/);
        this.setState({ loading: false });
        this.props.close();
      })
      .catch((e) => {
        errorMessage(e.response);
        this.setState({ loading: false });
      });
  };

  changeGrant = (value) => {
    this.getGrantDetail(value);
  };

  render() {
    const { selectedGrantArray, loading, grantType } = this.state;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    return (
      <Spin spinning={loading}>
        <Form className="contract-authorize new-form">
          <FormItem label={messages("finance-6.key147") /*授权引用人员范围*/}>
            {getFieldDecorator("grant", {
              initialValue: grantType ? grantType : "user",
              rules: [
                {
                  required: true,
                  message: messages("common.please.input") /*请输入*/,
                },
              ],
            })(
              <Select placeholder={messages("common.select") /*请选择*/} onChange={this.changeGrant}>
                <Option key={"user"} value={"user"}>
                  {messages("finance-6.key148") /*指定人员*/}
                </Option>
                <Option key={"user_group"} value={"userGroup"}>
                  {messages("basic-10.key63") /*指定人员组*/}
                </Option>
              </Select>
            )}
          </FormItem>
          <GrantRangeSelector
            grantCode={getFieldValue("grant")}
            selectedGrantArray={selectedGrantArray}
            onChangeSelected={this.onChangeSelectedGrantArray}
          />
          <div className="slide-footer">
            <Button type="primary" onClick={this.saveGrantDetail} loading={loading}>
              {messages("common.save") /*保存*/}
            </Button>
            &nbsp;&nbsp;&nbsp;
            <Button onClick={() => this.props.close()}>{messages("common.back") /*返回*/}</Button>
          </div>
        </Form>
      </Spin>
    );
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  };
}

const ContractAuthorizeForm = Form.create()(ContractAuthorize);
export default ContractAuthorizeForm;
